package com.jueming.cashbook.util;

/**
 * 雪花算法生成ID
 */
public class SnowFlake {
    /**
     * 设置起始时间戳，这里选择 2021-01-01 00:00:00 的时间戳
     */
    private static final long START_TIMESTAMP = 1609459200000L;
    /**
     * 机器ID所占的位数
     */
    private static final long WORKER_ID_BITS = 5L;
    /**
     * 数据中心ID所占的位数
     */
    private static final long DATACENTER_ID_BITS = 5L;
    /**
     * 序列号所占的位数
     */
    private static final long SEQUENCE_BITS = 12L;
    /**
     * 最大机器ID
     */

    private static final long MAX_WORKER_ID = -1L ^ (-1L << WORKER_ID_BITS);
    /**
     * 最大数据中心ID
     */
    private static final long MAX_DATACENTER_ID = -1L ^ (-1L << DATACENTER_ID_BITS);
    /**
     * 机器ID向左移12位
     */

    private static final long WORKER_ID_SHIFT = SEQUENCE_BITS;
    /**
     * 数据中心ID向左移17位
     */
    private static final long DATACENTER_ID_SHIFT = SEQUENCE_BITS + WORKER_ID_BITS;
    /**
     * 时间戳向左移22位
     */
    private static final long TIMESTAMP_LEFT_SHIFT = SEQUENCE_BITS + WORKER_ID_BITS + DATACENTER_ID_BITS;
    /**
     * 序列号的掩码，用于取出低12位的序列号
     */

    private static final long SEQUENCE_MASK = -1L ^ (-1L << SEQUENCE_BITS);
    /**
     * 机器ID
     */

    private static final long workerId=1;
    /**
     * 数据中心ID
     */
    private static final long datacenterId=1;
    /**
     * 序列号
     */
    private static long sequence = 0L;
    /**
     * 上次生成ID的时间戳
     */
    private static long lastTimestamp = -1L;

    public SnowFlake(long workerId, long datacenterId) {
        if (workerId > MAX_WORKER_ID || workerId < 0) {
            throw new IllegalArgumentException("Worker ID超出范围");
        }
        if (datacenterId > MAX_DATACENTER_ID || datacenterId < 0) {
            throw new IllegalArgumentException("Datacenter ID超出范围");
        }
        workerId = workerId;
        datacenterId = datacenterId;
    }

    public static synchronized long nextId() {
        long timestamp = System.currentTimeMillis();
        if (timestamp < lastTimestamp) {
            throw new RuntimeException("时钟回拨异常，请调整系统时钟");
        }
        if (timestamp == lastTimestamp) {
            sequence = (sequence + 1) & SEQUENCE_MASK;
            if (sequence == 0) {
                timestamp = tilNextMillis(lastTimestamp);
            }
        } else {
            sequence = 0L;
        }
        lastTimestamp = timestamp;
        return ((timestamp - START_TIMESTAMP) << TIMESTAMP_LEFT_SHIFT) |
                (datacenterId << DATACENTER_ID_SHIFT) |
                (workerId << WORKER_ID_SHIFT) |
                sequence;
    }

    private static long tilNextMillis(long lastTimestamp) {
        long timestamp = System.currentTimeMillis();
        while (timestamp <= lastTimestamp) {
            timestamp = System.currentTimeMillis();
        }
        return timestamp;
    }
}
